﻿namespace MoviesDataBase
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The movies data provider.
    /// </summary>
    public class DataProvider
    {
        /// <summary>
        /// The instance of the DataProvider.
        /// </summary>
        private static DataProvider instance;

        /// <summary>
        /// The data model entities.
        /// </summary>
        private MoviesDBEntities entities;

        /// <summary>
        /// Gets or sets the instance.
        /// </summary>
        /// <value>
        /// The instance.
        /// </value>
        public static DataProvider Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new DataProvider();
                }

                return instance;
            }

            set
            {
                instance = value;
            }
        }

        /// <summary>
        /// Gets or sets the entities.
        /// </summary>
        /// <value>
        /// The entities.
        /// </value>
        public MoviesDBEntities Entities
        {
            get
            {
                if (this.entities == null)
                {
                    this.entities = new MoviesDBEntities();
                }

                return this.entities;
            }

            set
            {
                this.entities = value;
            }
        }

        /// <summary>
        /// Inits this instance.
        /// </summary>
        public static void Init()
        {
            Instance.Entities.Connection.Open();
        }

        /// <summary>
        /// Adds the movie.
        /// </summary>
        /// <param name="movie">The movie.</param>
        public void AddMovie(Movie movie)
        {
            this.Entities.AddToMovies(movie);
            //this.Entities.SaveChanges();
        }

        /// <summary>
        /// Gets the movies.
        /// </summary>
        /// <returns>The list of the movies.</returns>
        public IEnumerable<Movie> GetMovies()
        {
            return this.Entities.Movies;
        }

        /// <summary>
        /// Gets the cast members.
        /// </summary>
        /// <returns>The cast members.</returns>
        public IEnumerable<CastMember> GetCastMembers()
        {
            return this.Entities.CastMembers;
        }

        /// <summary>
        /// Gets the movie.
        /// </summary>
        /// <param name="predicate">The predicate.</param>
        /// <returns>
        /// The movie with the same title.
        /// </returns>
        public Movie GetMovie(Func<Movie, bool> predicate)
        {
            return this.Entities.Movies.FirstOrDefault(predicate);
        }
    }
}
